package com.qfedu.web.filter;


import com.qfedu.pojo.User;
import com.qfedu.service.UserService;
import com.qfedu.service.impl.UserServiceImpl;
import com.qfedu.web.servlet.UserServlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * 创建者: QF-SUN
 * 创建时间: 2023/4/3 15:03
 * 描述:
 */
@WebFilter("/*")
public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1. 从session中获取 用户信息， 如果有，说明，已经登录成功，不需要自动登录
        Object user = request.getSession().getAttribute("user");
        if(user != null){
            filterChain.doFilter(request, response);
            return;
        }
        // 2. 否则需要自动登录
        //2.1. 获取cookie，从cookie查找用户信息
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            //遍历cookie， 查出需要的cookie
            for (Cookie cookie : cookies) {
                if("userInfo".equalsIgnoreCase(cookie.getName())){

                    String value = cookie.getValue();
                    //对cookie value解码， 切换， 判断数据库是否存在
                    String decode = URLDecoder.decode(value, "utf-8");
                    if(decode != null){
                        String[] arr = decode.split("#");
                        if(arr != null && arr.length == 2){
                            UserService userService = new UserServiceImpl();
                            User loginUser = userService.login(arr[0], arr[1]);
                            if(loginUser != null){
                                request.getSession().setAttribute("user", loginUser);
                                filterChain.doFilter(request, response);
                                return;
                            }
                        }
                    }

                }
            }
        }
        //没有登录，也没有自动登录，也放行
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
